<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { eventById, eventnodeuserApi } from '@/service/api.ts';
import { downloadFiles, isJSON, isMiniProgram } from '@/utils/utils.ts';
import { showConfirmDialog, showToast } from "vant";
import { useConstValue, useLocalValue, useIuserInfoStore } from '@/store/users.ts';
import { api } from '@/plugins/env-config.ts';
import fileDownload from 'js-file-download';
import dayjs from 'dayjs';
import SheetSvg from '~icons/svg/sheet';
import BtnSvg from '~icons/svg/btn';
import PraiseSvg from '~icons/svg/praise';

const route = useRoute();
const { eventID, tab } = route.query;
const router = useRouter();
const constValue = useConstValue();
const localValue = useLocalValue();
const iuserInfoStore = useIuserInfoStore();

const labelMap = {
  '会议': 'PropertyMeet',
  '投票': 'PropertyVote',
  '征询': 'PropertyAdvice',
  '公示': 'PropertyAnnounce',
};

onMounted(() => {
  getEventDetail(eventID);
});
const eventRf = ref(null);
const nodeuserRf = ref(null);
const getEventDetail = async (id) => {
  const type = labelMap[tab];
  if (!type) {
    return;
  }
  const event = await eventById({ method: 'get', id, });
  if (!event.id || !isJSON(event.form_data)) {
    return;
  }
  if (isJSON(event.request_params)) {
    event._request_params = JSON.parse(event.request_params);
  }
  
  const arrs = JSON.parse(event.form_data);
  const signs = arrs.filter(item => item.sign);
  if (!signs.length) {
    return;
  }
  event._sign = {};
  signs.forEach(item => {
    event._sign[item.sign] = item.value;
  });
  event._form_data = arrs.filter(i => !i.sign);
  nodeuserRf.value = null;
  const nodeusers = await getEventnodeuserList(event);
  nodeuserRf.value = nodeusers?.length ? nodeusers[0] : {};
  eventRf.value = event;
}
const getEventnodeuserList = (event) => {
  return new Promise((resolve, reject) => {
    eventnodeuserApi({
      method: 'get',
      params: {
        event: event.id,
        node: event.node,
        item: localValue.r_id,
      }
    }).then(res => {
      resolve(res?.results || []);
    }).catch(err => {
      reject([]);
    })
  })
}

const handleVote = (vote) => {
  if (canVote.value === 1) {
    showToast('投票已结束！');
    return;
  }
  if (vote === '反对' && !nodeuserRf.value.txt) {
    showToast('请填写反对意见！');
    return;
  }
  showConfirmDialog({
  	title: vote,
  	message: nodeuserRf.value.txt,
  }).then(() => {
    eventnodeuserApi({
      method: 'post',
      data: {
        event: eventID,
        create_user: localValue.mainUser.user,
        node: eventRf.value.node,
        type: labelMap[tab],
        project: constValue.projectID,
        txt: nodeuserRf.value.txt,
        mark: vote,
        item: localValue.r_id,
      }
    }).then(res => {
      showToast('提交成功！');
      router.go(-1);
    });
  }).catch(() => {
  	// on cancel
  });
}

const canVote = computed(() => {
  const { endtime } = eventRf.value?._sign || {};
  if (!endtime) {
    return 0;
  }
  if (dayjs().isAfter(endtime)) {
    return 1;
  } else {
    return 2;
  }
});

const handleDownFile = (file) => {
  showConfirmDialog({
  	title: '下载提示',
  	message: `是否下载文件${ file.name }`,
  }).then(() => {
    if (isMiniProgram) {
      if (window.webkit?.messageHandlers?.postMessage) {
        /* 向小程序发送下载请求 */
        window.webkit.messageHandlers.postMessage.postMessage({
          action: 'download',
          fileUrl: api + file.url,
        });
      } else if (window.AndroidInterface){
        /* 向Android发送下载请求 */
        window.AndroidInterface.downloadFile(api + file.url);
      } else if (window.webkit?.messageHandlers?.downloadFileHandler) {
        /* 向ios发送下载请求 */
        window.webkit.messageHandlers.downloadFileHandler.postMessage(api + file.url);
      }
    } else {
      downloadFiles(file.name, file.url);
    }
  }).catch(() => {
  	// on cancel
  });
}
</script>

<template>
  <div class="content flex-column scroller-aside">
    <div class="name-event flex--center">
      <SheetSvg color="#00B578"/>
      <div class="ellipsis" style="margin: 0 10px;flex: 1;">{{ eventRf?._sign?.name }}</div>
      <div
        class="title_vote flex-nowrap flex--center"
        :class="{ 'neg': nodeuserRf.mark === '反对'}"
        v-if="nodeuserRf?.id"
      >
        <PraiseSvg />
        <span>已{{ nodeuserRf.mark }}</span>
      </div>
    </div>
    
    <div class="time-row flex--center" v-if="eventRf?._sign">
      <label>截止时间：</label>
      <p>{{ dayjs(eventRf._sign.endtime).format('YYYY-MM-DD HH:mm') }}</p>
    </div>
    
    <template v-for="item in (eventRf?._form_data || [])">
      <label class="bord-label">{{ item.label }}</label>
      <p class="form-value">{{ item.value }}</p>
    </template>
    
    <template v-for="list in eventRf?._request_params?.filter(i => i.UDID === 'uploadAttachment')">
      <div class="time-row flex--center">
        <label>{{ list.label }}：</label>
        <div class="flex-column" style="gap: 5px;">
          <p class="flex--center" v-for="item in list.value" @click="handleDownFile(item)">
            <van-icon name="link-o" />
            <span style="margin-left: 5px;">{{ item.name }}</span>
          </p>
        </div>
      </div>
    </template>
    
    <template v-if="tab != '公示' && canVote && nodeuserRf && !nodeuserRf.id">
      <label class="bord-label" style="margin-top: 24px;">我的意见</label>
      <textarea v-model="nodeuserRf.txt" rows="6" placeholder="期待您的意见，帮助我们做的更好" maxlength="200"/>
      
      <div class="button-container flex-sb">
        <div class="btn-box" @click="handleVote('反对')">
          <BtnSvg color="#E70101" />
          <div class="text neg flex--center">
            <PraiseSvg />反对
          </div>
          
        </div>
        <div class="btn-box right" @click="handleVote('赞成')">
          <BtnSvg color="#009245" />
          <div class="text flex--center">
            <PraiseSvg />赞成
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<style lang="scss" scoped>
.content {
  width: 100vw;
  height: 100vh;
  padding: 0 12px;
  overflow: auto;
  background-color: #fff;
}
.name-event {
  height: 46px;
  border-bottom: 1px solid #E0E0E0;
  font-weight: 500;
  font-size: 16px;
  color: #000000;
  span {
    margin-left: 5px;
  }
}
.title_vote {
  color: #00B578;
  font-size: 14px;
  svg {
    width: 16px;
    height: 16px;
    margin-right: 4px;
  }
  &.neg {
    color: #FF0000;
    svg {
      transform-origin: center;
      transform: rotate(180deg);
    }
  }
}
label.bord-label {
  margin-top: 12px;
  font-weight: 500;
  font-size: 16px;
  color: #111111;
}
.time-row {
  width: 100%;
  overflow: hidden;
  margin-top: 10px;
  align-items: flex-start;
  label, p {
    font-size: 14px;
  }
  label {
    min-width: 72px;
  }
  .flex-column p {
    color: #1890FF;
  }
}
p.form-value {
  font-weight: 400;
  font-size: 14px;
  color: #111111;
}
p.form-value {
  margin-top: 8px;
}
textarea {
  padding: 10px;
  background-color: #F3F3F3;
  border: none;
  border-radius: 8px 8px 8px 8px;
  color: #000000;
  &:focus-visible {
    outline: none;
  }
}

.button-container {
  margin-top: 24px;
  position: relative;
  .btn-box {
    position: absolute;
    width: 53%;
    line-height: 0;
    overflow: hidden;
    svg {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
    .text {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-53%, -50%);
      color: white;
      font-size: 14px;
      svg {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
      &.neg svg {
        transform-origin: center;
        transform: rotate(180deg);
      }
    }
  }
  .btn-box.right {
    position: absolute;
    right: 0;
    width: 53%;
    >svg {
      transform-origin: center;
      transform: rotate(180deg);
    }
  }
}
</style>